<?php
namespace app\common\model\logic;

use think\Model;

class CmsArticleModel extends Model {

    protected $name = 'cms_article'; //定义栏目表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    //类型自动转换
    protected $type = [
        'sort'=>'integer',
        'click'=>'integer'
    ];
	//格式化列表
    public function formatList($list){
        return $list;
    }
    //格式化单条内容
    public function formatInfo($info){
        return $info;
    }
    //富文本编码
    protected function getContentAttr($value)
    {
        return stripslashes(htmlspecialchars_decode($value));
    }
    //扩展属性读取器
    public function getExtendAttr($value, $data)
    {
        if(empty($value)){
            return [];
        }
        return json_decode($value,true);
    }

    //扩展属性设置器
    protected function setExtendAttr($value, $data)
    {
        $item = [];
        if ($value) {
            $value = trim($value);
            $list = explode("\r\n", $value);
            foreach($list as $v){
                $v = trim($v);
                 if(!empty($v)){
                     $v = str_replace('：',":",$v);
                     $arr = explode(':',$v);
                     $arrKey = trim($arr[0]);
                     $arrValue = trim($arr[1]);
                     $item[$arrKey] = $arrValue;
                }
            }
        }
        return json_encode($item,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取检索条件
     * @param $query
     */
    public function getExtendMap($query){
        return [];
    }

    //读取单条数据
    public function read($aid){
        try{
            $info = $this->get($aid)->toArray();
            return $info;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //添加数据
    public function add($data){
        try{
            $this->isUpdate(false)->allowField(true)->save($data);
            return true;
        }catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //修改数据
    public function edit($data){
        try{
            if (!$this->request->has('extend')) {
                $data['extend'] = '';
            }
            $this->isUpdate(true)->allowField(true)->save($data);
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //删除数据
    public function del($aid){
        try{
            $this->destroy($aid);
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
}